package com.btm.experimental.alldemo;

import redis.clients.jedis.Jedis;

import java.util.Random;

/**
 * 频道消息的发布者线程，模拟一直在发消息
 *
 * @Author: btm
 * @Date: 2021/1/18 10:26
 * @Description:
 */
public class MsgPublisher implements Runnable{

    private boolean print = false;

    public MsgPublisher(boolean print) {
        this.print = print;
    }

    public void run() {
        Jedis jedis = RedisContactPool.getJedisContact();
        String threadName = Thread.currentThread().getName();
        int i = 0;
        while (true) {
            Random msgRandom = new Random();
            String message = threadName+"["+i+"]"+RedisInfo.SEPARATOR+msgRandom.nextInt(10000)+"";
            jedis.publish(RedisInfo.SUBSCRIBE_NAME, message);
            Random sleepRandom = new Random();
            try {
                i ++;
                int sleep = sleepRandom.nextInt(1000);
                if (print) {
                    System.out.println(threadName + " send message[" + i + "] to [" + RedisInfo.SUBSCRIBE_NAME + "]:[" + message + "]");
                }
                Thread.sleep(sleep);
                if (i == 50) {
                    return;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
